package com.example.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.service.AdminService;
import com.example.entity.Admin;
import com.example.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 日期：2025/5/2 14:50
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Resource
    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        //1.从http请求的header中获取token
        String token = request.getHeader("token");
        //如果header中不存在token，则从url参数中获取
        if(StrUtil.isBlank(token)){
            //从url中获取token
            token = request.getParameter("token");
        }
        //2.开始执行token的验证
        //如果token为空，则抛出异常
        if(StrUtil.isBlank(token)){
            throw new CustomException("无token，请重新登录2");
        }
        String userId;
        Admin admin;
        //解析token
        try {
            //获取token中的用户id
            userId = JWT.decode(token).getAudience().get(0);
            //根据用户id查询用户信息
            admin = adminService.findByById(Integer.parseInt(userId));
        } catch (Exception e) {
            String errMsg = "token解析失败，请重新登录";
            log.error( errMsg +"token验证失败"+ token, e);
            throw new CustomException(errMsg);
        }
        //如果用户不存在，则抛出异常
        if(admin == null){
            throw new CustomException("用户不存在，请重新登录");
        }
        //验证token
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
            jwtVerifier.verify(token);
        }catch (JWTVerificationException e){
            throw new CustomException("token验证失败，请重新登录");
        }
        log.info("token验证成功，用户id："+ userId);
        return true;
    }
}
